# 取出数据库中所有的订单 id。扩充时，在订单id后加"_{重复次数}"
from ws4py.client.threadedclient import WebSocketClient
import json, threading, time
import pandas as pd
import numpy as np

class DemandClient(WebSocketClient):

    def __init__(self, url, demand_id, lon, lat):
        super().__init__(url)
        self.demand_id = demand_id
        self.lon = lon
        self.lat = lat
        self.timer = threading.Timer(60, self.cancel)
        self.timer.start()

    def cancel(self):
        self.send(json.dumps({"type": "cancel",
                              "demand_id": self.demand_id
                              }))
        self.timer.cancel()
        self.close()

    def opened(self):  # socket连接后调用
        print("open!")

    def closed(self, code, reason=None):  # wk关闭时调用
        print(code, time.strftime('%Y-%m-%d %H:%M:%S'))

    def received_message(self, message):  # 长连接时接收socket的所有消息,可根据消息做对应处理
        if str(message) == "success":
            print(self.demand_id + " success")
            self.timer.cancel()
            self.close()

def start_demand(id, lon, lat):
    ws = DemandClient("ws://localhost:8090/websocket/demand/" + str(id), id, lon, lat)
    message = json.dumps({
        "type": "info",
        "id": id,
        "lon": lon,
        "lat": lat
    })
    ws.connect()
    ws.send(message)
    ws.run_forever()


if __name__ == '__main__':
    appear_num_max = 2;
    appear_prob = 0.3
    demand_id_dic = {}
    demand_infos = pd.read_csv("data/demand_loc.csv").values
    demand_info_length = len(demand_infos)
    while True:
        if np.random.rand() > appear_prob:
            time.sleep(1)
            continue
        demand_num = int(np.random.rand() * appear_num_max)
        for i in range(demand_num):
            demand_info = demand_infos[int(np.random.rand() * demand_info_length)]
            if demand_info[0] in demand_id_dic.keys():
                demand_id_dic[demand_info[0]] += 1
            else:
                demand_id_dic[demand_info[0]] = 1
            th = threading.Thread(target=start_demand,
                                  args=(str(int(demand_info[0])) + "+" + str(demand_id_dic[demand_info[0]]),
                                        float(demand_info[2]),
                                        float(demand_info[1])))
            th.start()
        time.sleep(1)
    #
    # th = threading.Thread(target=start_demand,
    #                       args=("17120720+1",
    #                             114.17121000000002,
    #                             22.3249331))
    # th.start()
    # th = threading.Thread(target=start_demand,
    #                       args=("17120720+2",
    #                             114.1472591,
    #                             22.3860011))
    # th.start()

    # th = threading.Thread(target=start_demand,
    #                       args=("17122233+1",
    #                             114.17121000000002,
    #                             22.3249331))
    # th.start()
    #
    # th = threading.Thread(target=start_demand,
    #                       args=("17122233+2",
    #                             114.17121000000002,
    #                             22.3249331))
    # th.start()